package com.ruoyi.web.controller.project;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.system.domain.ProjectPurchaseMaterial;
import com.ruoyi.system.domain.ProjectUser;
import com.ruoyi.system.service.IMessageService;
import com.ruoyi.system.service.IProjectPurchaseMaterialService;
import com.ruoyi.system.service.IProjectUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProjectPurchase;
import com.ruoyi.system.service.IProjectPurchaseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目申请Controller
 * 
 * @author ruoyi
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/project/purchase")
@RequiredArgsConstructor
@Api(tags = "项目申请")
public class ProjectPurchaseController extends BaseController{

    private final IProjectPurchaseService projectPurchaseService;

    private final IProjectPurchaseMaterialService projectPurchaseMaterialService;

    private final IMessageService messageService;

    private final IProjectUserService projectUserService;


    @GetMapping("/list")
    @ApiOperation("查询项目申请列表")
    public TableDataInfo list(@RequestParam(value = "projectId",required = false)Integer projectId,
                              @RequestParam(value = "userId",required = false)Long userId,
                              @RequestParam(value = "purchaseUserId",required = false)Long purchaseUserId)
    {
        startPage();
        QueryWrapper<ProjectPurchase> wrapper = new QueryWrapper<>();
        if (projectId != null){
            wrapper.eq("project_id",projectId);
        }
        if (userId != null){
            wrapper.eq("user_id",userId);
        }
        if (purchaseUserId != null){
            QueryWrapper<ProjectUser> projectUserQueryWrapper = new QueryWrapper<>();
            projectUserQueryWrapper.eq("user_id",purchaseUserId);
            List<ProjectUser> projectUserList = projectUserService.list(projectUserQueryWrapper);
            if (projectUserList != null && projectUserList.size() > 0){
                wrapper.in("project_id",projectUserList.stream().map(ProjectUser::getProjectId).collect(Collectors.toList()));
            }
        }
        wrapper.orderByDesc("created_time");
        List<ProjectPurchase> list = projectPurchaseService.list(wrapper);
        for (ProjectPurchase projectPurchase : list) {
            QueryWrapper<ProjectPurchaseMaterial> projectPurchaseMaterialQueryWrapper = new QueryWrapper<>();
            projectPurchaseMaterialQueryWrapper.eq("project_purchase_id",projectPurchase.getId());
            List<ProjectPurchaseMaterial> projectPurchaseMaterialList = projectPurchaseMaterialService.list(projectPurchaseMaterialQueryWrapper);
            projectPurchase.setProjectPurchaseMaterialList(projectPurchaseMaterialList);
        }
        return getDataTable(list);
    }



    @GetMapping(value = "/{id}")
    @ApiOperation("获取项目申请详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        ProjectPurchase projectPurchase = projectPurchaseService.getById(id);
        QueryWrapper<ProjectPurchaseMaterial> projectPurchaseMaterialQueryWrapper = new QueryWrapper<>();
        projectPurchaseMaterialQueryWrapper.eq("project_purchase_id",projectPurchase.getId());
        List<ProjectPurchaseMaterial> projectPurchaseMaterialList = projectPurchaseMaterialService.list(projectPurchaseMaterialQueryWrapper);
        projectPurchase.setProjectPurchaseMaterialList(projectPurchaseMaterialList);
        return success(projectPurchase);
    }


    @Log(title = "项目申请", businessType = BusinessType.INSERT)
    @ApiOperation("新增项目申请")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ProjectPurchase projectPurchase)
    {
        projectPurchase.setCreatedTime(new Date());
        projectPurchase.setUserId(getUserId());
        projectPurchase.setUserName(getNickName());
        projectPurchase.setStatus(0);
        boolean save = projectPurchaseService.save(projectPurchase);
        projectPurchase.getProjectPurchaseMaterialList().forEach(
                m->{
                    m.setProjectPurchaseId(projectPurchase.getId());
                    m.setStatus(0);
                    projectPurchaseMaterialService.save(m);
                }
        );
        messageService.sendProjectMsgByRoleIds(projectPurchase.getProjectId(),"111", projectPurchase.getUserName()+"新增"+projectPurchase.getTitle());
        return toAjax(save);
    }


    @Log(title = "项目申请", businessType = BusinessType.UPDATE)
    @ApiOperation("修改项目申请")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody ProjectPurchase projectPurchase)
    {
        boolean result = projectPurchaseService.updateById(projectPurchase);
        QueryWrapper<ProjectPurchaseMaterial> materialQueryWrapper = new QueryWrapper<>();
        materialQueryWrapper.eq("project_purchase_id",projectPurchase.getId());
        projectPurchaseMaterialService.remove(materialQueryWrapper);
        projectPurchase.getProjectPurchaseMaterialList().forEach(
                m->{
                    m.setProjectPurchaseId(projectPurchase.getId());
                    m.setStatus(0);
                    projectPurchaseMaterialService.save(m);
                }
        );
        messageService.sendProjectMsgByRoleIds(projectPurchase.getProjectId(),"111", projectPurchase.getUserName()+"修改"+projectPurchase.getTitle());
        return toAjax(result);
    }


    @Log(title = "项目申请", businessType = BusinessType.DELETE)
    @ApiOperation("删除项目申请")
	@PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        for (Integer id : ids) {
            QueryWrapper<ProjectPurchaseMaterial> materialQueryWrapper = new QueryWrapper<>();
            materialQueryWrapper.eq("project_purchase_id",id);
            projectPurchaseMaterialService.remove(materialQueryWrapper);
        }
        return toAjax(projectPurchaseService.removeBatchByIds(Arrays.asList(ids)));
    }

//    public AjaxResult withdraw(@RequestParam("id")Integer id){
//        messageService.sendProjectMsgByRoleIds(projectPurchase.getProjectId(),"111", projectPurchase.getUserName()+"新增"+projectPurchase.getTitle());
//
//    }

}
